<?php
	
	class Database extends Object  {
		
		protected static $connections = array();
		
		public static function connect($identifier, $database_options) {
			
			if(array_key_exists($identifier, self::$connections)) {
				throw new ConnectionExistsException(
					sprintf(_('Error: connection already exists. identifier=%s'), $identifier))
				);
			}
			
			if(!is_array($database_options)) {
				throw new ConnectionException(_('Database options paramater should be an array.'));
			}
			
			if(!array_key_exists('type', $database_options)) {
				throw new ConnectionException(_('Error: database type not specified'));
			}
			
			if(!array_key_exists('database', $database_options)) {
				throw new ConnectionException(_('Error: database name not specified.'));
			}
			
			if(!array_key_exists('user', $database_options)) {
				throw new ConnectionException(_('Error: database user not set'));
			}
			
			if(!array_key_exists('password', $database_options)) {
				throw new ConnectionException(_('Error: database password not set'));
			}
			
			$dsn = sprintf('%s:dbname=%s;host=%s;charset=%s',
				$database_options['type'],
				$database_options['database'],
				array_key_exists('host',$database_options) ? $database_options['host'] : 'localhost',
				array_key_exists('charset',$database_options) ? $database_options['charset'] : 'utf8'
			);
			
			$db = new PDO($dsn, $database_options['user'], $database_options['password']);
			
			self::$connections[$identifier] = $db;
			
		}
		
		public static function &fetchConnection($identifier) {
			
			if(!array_key_exists($identifier, self::$connections)) {
				throw new ConnectionException(_('Connection undefined'));
			}
			
			return self::$connections[$identifier];
		}
		
		public static function disconnect($identifier) {
			
			if(!array_key_exists($identifier, self::$connections)) {
				throw new ConnectionException(_('Connection undefined'));
			}
			
			self::$connections[$identifier] = NULL;
			unset(self::$connections[$identifier];
		}
		
		public static function disconnectAll() {
			
			self::$connections = array();
			
		}
		
		public static function reconnect($identifier, $database_options) {
			
			self::disconnect($identifier);
			self::connect($identifier, $database_options);
		}
		
		private function __construct() {}
		private function __destruct() {}
		private function __clone() {}
		
	
	}